/*
 * UserNet  --  TCP/IP implementation in userspace
 * Copyright (C) 2010  Robert Millan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stddef.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>

#include "unet/misc.h"
#include "unet/ipc.h"

int
unet_ipc_connect ()
{
  struct sockaddr_un addr;
  int fd;

  errno = 0;

  fd = socket (AF_UNIX, SOCK_STREAM, 0);
  if (fd < 0)
    {
      errno = ENETDOWN;
      return -1;
    }

  addr.sun_family = AF_UNIX;

  COMPILE_TIME_ASSERT (sizeof (addr.sun_path) > sizeof (SERVER_SOCKET));
  strcpy (addr.sun_path, SERVER_SOCKET);

  if (connect (fd, (struct sockaddr *) &addr, sizeof (addr)) == -1)
    {
      close (fd);
      errno = ENETDOWN;
      return -1;
    }

  return fd;
}
